/**
 * @author SIAGO HAPPI Christelle
 */
package model.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.audio.AudioData;
import sun.audio.AudioDataStream;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;


 public class Audio {
    
    // The audio file
    private File fichier;
    // audio data
    private AudioData data;
   // the disable input stream for this data
    private InputStream inputStr ;
  
   
    
    
    /**
     * Creation and audio file playback
     * @param filename   name of the sound file to play
     */
    public Audio(String filename)
    {
        fichier = null;
        data = null;
        inputStr = null;
        jouerAudio(filename);
    }
    
    
    /**
    * Stop a current file if needed
    */
    private void stopCurrentAudio()
    {     
        if (inputStr != null) {
            AudioPlayer.player.stop(inputStr);
            inputStr = null;
        }
    }
    
    
     /**
     * Play the audio file
     * @param filename  name of the sound file to play
     */
     private void jouerAudio(String filename){
         fichier = new File(filename);
         if(fichier!=null)
         {      
                AudioStream as = null;
                try {

                    FileInputStream fis = new FileInputStream(fichier);
                    as = new AudioStream(fis);
                    data = as.getData();
                    stopCurrentAudio();
                    if (data != null) {
                        // An audio stream redirected to our input stream is Created
                        AudioDataStream ads = new AudioDataStream(data);
                        // start reading
                        AudioPlayer.player.start(ads);
                        inputStr = ads;
                    }
                } catch (IOException ex) {
                    Logger.getLogger(Audio.class.getName()).log(Level.SEVERE, null, ex);
                }
                finally {
                    try {
                        as.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Audio.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
          }
    }

 }
